const Promise = require('bluebird');
const Ticket = require('../models/ticket');
const Log = require('../models/log');

module.exports = function(tickets, userId, operation) {
    const processor = function(t) {
        return Promise.try(() => {
            return tickets;
        })
        .map(item => {
            if(item.status === Ticket.UNUSED && operation === '票券激活') {
                item.end_time = new Date(Date.now() + (+item.days * 24 * 60 * 60 * 1000));
            }
            return Ticket.where({
                id: item.id
            })
            .save({
                status: item.status,
                b_percent: item.b_percent,
                updated_at: new Date(),
                start_time: new Date(item.start_time * 1000),
                deleted: item.deleted,
                // end_time: item.end_time
            }, {
                method: 'update',
                transacting: t,
            })
            .then(ticket => {
                return Log.safeForge({
                    creator: userId,
                    ticket_id: item.id,
                    type: operation
                })
                .save({}, {
                    transacting: t,
                });
            });
        });
    };
    return Ticket.buildTransaction(processor);
};
